package com.lagou.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(7001));

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        SocketChannel accept = serverSocketChannel.accept();

        int maxLen = 8;

        while (true) {
            int readLen = 0;
            while (readLen < maxLen) {
                int read = (int) accept.read(byteBuffers);
                readLen += read;
                System.out.println("byterread is :" + readLen);
                Arrays.stream(byteBuffers)
                        .map(buffer -> "position is " +  buffer.position() +  ", limit is :" + buffer.limit())
                        .forEach(System.out::println);
            }


            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());

            int writeLen = 0;
            while (writeLen < maxLen) {
                int write = (int) accept.write(byteBuffers);
                writeLen += write;
            }

            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());

            System.out.println("read length is " + readLen + ", and write length is : " + writeLen);

        }

    }
}
